<div class="image-dialog" id="dialog">
    <div class="image-dialog-head layui-col-space10">
        <label class="pull-left">
            <select class="layui-select" v-model="province_code" @change="onProvinceChange">
                <option value="">选择省份</option>
                <option v-for="(item,index) in provinces" :value="item.code" :data-center="item.center">{{item.name}}
                </option>
            </select>
        </label>
        <label class="pull-left">
            <select class="layui-select" v-model="city_code" :disabled="!province_code" @change="onCityChange">
                <option value="">选择城市</option>
                <option v-for="(item,index) in cities" :value="item.code" :key="item.code" :data-center="item.center">{{item.name}}
                </option>
            </select>
        </label>
        <label class="pull-left">
            <select class="layui-select" v-model="district_code" :disabled="!city_code" @change="onDistrictChange">
                <option value="">选择区</option>
                <option v-for="(item,index) in districts" :value="item.code" :key="item.code" :data-center="item.center">{{item.name}}
                </option>
            </select>
        </label>
        <label class="pull-left flex">
            <input class="layui-input margin-right-5" disabled v-model="keyword" style="height:30px;line-height:30px"
                   placeholder="{:lang('请输入搜索关键词')}">
            <a class="layui-btn layui-btn-sm layui-btn-normal" @click="search">{:lang('搜 索')}</a>
        </label>

        <div class="pull-right">
            <a class="layui-btn layui-btn-sm layui-btn-normal" @click="close">确定</a>
        </div>
    </div>
    <div class="image-dialog-body" :id="id" style="width: 100%; height: 500px"></div>
</div>


<style>
    .layui-layer-page .layui-layer-content {
        overflow: hidden;
    }

    .pull-left .layui-select {
        height: 30px;
        line-height: 30px
    }

    .custom-content-marker {
        position: relative;
        width: 25px;
        height: 34px;
    }

    .custom-content-marker img {
        width: 100%;
        height: 100%;
    }

    .custom-content-marker .close-btn {
        position: absolute;
        top: -6px;
        right: -8px;
        width: 15px;
        height: 15px;
        font-size: 12px;
        background: #ccc;
        border-radius: 50%;
        color: #fff;
        text-align: center;
        line-height: 15px;
        box-shadow: -1px 1px 1px rgba(10, 10, 10, .2);
    }

    .custom-content-marker .close-btn:hover {
        background: #666;
    }
</style>
<script>
    require(['jquery', 'vue', 'amap'], function ($, vue, AMap) {
        window.app = new vue({
            el: '#dialog',
            data: {
                provinces: [],
                province_code: '',
                cities: [],
                city_code: '',
                districts: [],
                district_code: '',
                map_path: '',

                didx: 0,//弹窗索引
                keyword: '',
                idx: 0,
                id: 'container',
                lng: '',
                lat: '',
                address: '',
                // apiKey: '01b97234c54eeccd83538eb467f52357',
                apiKey: '44d52629359868876660ac48972d2a2f',
                marker: null,
                markerContent: '<div class="custom-content-marker"><img src="/static/extra/marker-default.png"></div>',
                map: null,
                script: null,
            },
            methods: {
                getJson: function (url, func, callback) {
                    let self = this;
                    window[func] = function (data) {
                        callback(data);
                        self.removeScript();

                    };
                    this.script = document.createElement("script");
                    this.script.setAttribute("src", url);
                    document.getElementsByTagName("head")[0].appendChild(this.script);
                    this.script.onload = this.script.onreadystatechange = function (data) {
                        window[func] = null;
                    };
                },
                onProvinceChange: function (event) {
                    console.log('event---->', event)
                    this.city_code = '';
                    this.district_code = '';
                    this.cities = [];
                    this.districts = [];
                    const opt = event.target.selectedOptions[0];
                    console.log('opt-->', opt)
                    if (this.province_code) {
                        // this.setCenter(opt.getAttribute('data-lng'), opt.getAttribute('data-lat'), 6);
                        this.setCenter(opt.getAttribute('data-center'), 6);
                        this.cities = this.getRegion(this.province_code);
                    }
                },
                onCityChange: function (event) {
                    console.log('event---->', event)
                    const opt = event.target.selectedOptions[0];
                    console.log('opt-->', opt)
                    this.district_code = '';
                    this.districts = [];
                    console.log('city_code----->', this.city_code)
                    if (this.city_code) {
                        this.setCenter(opt.getAttribute('data-center'), 10);
                        this.districts = this.getRegion(this.city_code);
                    }
                },
                onDistrictChange: function (event) {
                    console.log('event---->', event)
                    const opt = event.target.selectedOptions[0];
                    console.log('opt-->', opt)
                    console.log('district_code----->', this.district_code)
                    if (this.district_code) {
                        this.setCenter(opt.getAttribute('data-center'), 13);
                    }
                },

                removeScript: function () {
                    document.getElementsByTagName("head")[0].removeChild(this.script);
                },

                search: function () {
                    let self = this;
                    let url = encodeURI(
                        "https://apis.map.qq.com/ws/geocoder/v1/?address=" + encodeURI(this.keyword) + "&boundary=region(" + this.keyword + ",0)&page_size=9&page_index=1&key=ZI5BZ-N5667-YRLX5-HT23K-QWQJ2-FIFCF&output=jsonp&&callback=?"
                    );
                    self.getJson(url, "QQmap", function (res) {
                        console.log("res", res)
                        if (res.status === 0) {
                            res = res.result;
                            self.lat = res.location.lat;
                            self.lng = res.location.lng;
                            self.address = res.address;
                            self.district_code = res.ad_info.adcode;
                            window['getJson'] = null;
                            self.setInput();
                            // $.msg.close(self.didx);
                        }
                    });

                },
                close: function () {
                    $.msg.close(this.didx);
                },
                // 设置选择数据
                setValue: function (xurl) {
                    $.msg.close(this.didx);
                    this.$btn.triggerHandler('push', xurl);
                    return this;
                },
                setCenter: function (location, zoom) {
                    if (this.map &&  location) {
                        let [lng, lat] = location.split(',');
                        this.map.setCenter([lng, lat]);
                        this.map.setZoom(zoom || 15);
                    }
                },
                getRegion: function (code) {
                    let ret = null;
                    $.ajax({
                        url: '/admin/api.region/index',
                        data: {parent_code: code},
                        dataType: 'json',
                        type: 'POST',
                        async: false,
                        success: function (data) {
                            console.log("res==>", data)
                            ret = data.data;
                        }
                    });
                    return ret;
                },

                initMap: function () {
                    let self = this;
                    // 地图中心点
                    let position = new AMap.LngLat(114.290197,24.060092);
                    if (self.lng && self.lat) {
                        position = new AMap.LngLat(self.lng, self.lat);
                    }
                    // 创建地图实例
                    this.map = new AMap.Map(self.id, {
                        zoom: 15,
                        center: position,
                        resizeEnable: true,
                    });
                    this.marker = new AMap.Marker({
                        position: position,
                        content: this.markerContent,
                        // 以 icon 的 [center bottom] 为原点
                        offset: new AMap.Pixel(-13, -30)
                    });
                    this.map.add(this.marker);
                    // 地图点击事件
                    this.map.on('click', self.addMarker);
                },
                removeMark: function () {
                    console.log("remove~~~")
                    if (this.map && this.marker) {
                        this.map.remove(this.marker);
                        this.marker = null;
                    }
                },
                addMarker: function (e) {
                    this.removeMark();//删除之前添加的marker
                    console.log("click----->", e)
                    this.lat = e.lnglat.lat;
                    this.lng = e.lnglat.lng;
                    this.marker = new AMap.Marker({
                        position: new AMap.LngLat(this.lng, this.lat),
                        content: this.markerContent,
                        // 以 icon 的 [center bottom] 为原点
                        offset: new AMap.Pixel(-13, -30)
                    });
                    // 将 markers 添加到地图
                    this.map.add(this.marker);
                    //坐标保存到目标元素中
                    this.setInput();
                    // 逆地址解析-获得详细地址
                    let self = this;
                    let url = encodeURI(`https://restapi.amap.com/v3/geocode/regeo?key=2f02a3b9f0176753d5f5ddacc430dc5f&location=${self.lng},${self.lat}&callback=xx`);
                    self.getJson(url, "xx", function (res) {
                        console.log("res", res)
                        if (res.infocode === "10000") {
                            self.address = res.regeocode.formatted_address;
                            self.district_code = res.regeocode.addressComponent.adcode;
                            window['getJson'] = null;
                            self.setInput();
                        }
                    });
                },
                setInput: function () {
                    if (this.$btn.data('lat')) {
                        $(this.$btn.data('lat')).val(this.lat).trigger('change');
                    }
                    if (this.$btn.data('lng')) {
                        $(this.$btn.data('lng')).val(this.lng).trigger('change');
                    }
                    if (this.$btn.data('address')) {
                        $(this.$btn.data('address')).val(this.address).trigger('change');
                    }
                    if (this.$btn.data('code')) {
                        $(this.$btn.data('code')).val(this.district_code).trigger('change');
                    }

                },
                choseItem(item) {
                    console.log('选择坐标===》', item)
                    let self = this;
                    self.map.panTo(new qq.maps.LatLng(item.location.lat, item.location.lng));
                    self.map.zoomTo(20);
                }
            },
            created: function () {
                this.didx = $.msg.mdx.pop();
                this.$btn = $('#{$get.id|default=""}');
                if (this.$btn.data('lat')) {
                    this.lat = $(this.$btn.data('lat')).val();
                }
                if (this.$btn.data('lng')) {
                    this.lng = $(this.$btn.data('lng')).val();
                }
                // console.log("lat", this.lat)
                // console.log("lng", this.lng)
                // console.log("btn", this.$btn)
            },
            mounted() {
                self = this;
                this.provinces = this.getRegion(null);
                this.$nextTick(() => {
                    this.initMap();
                    $(document).on("click", ".custom-content-marker", function (e) {
                        self.removeMark(e)
                    })
                })

            },
        });
    });
</script>